package service

import (
	"context"
	"encoding/json"
	"github.com/forgoer/openssl"
	"github.com/sirupsen/logrus"
	"golang.org/x/crypto/ssh"
	"log"
	"my-desktop/config"
	"my-desktop/sshDesktop"
	"os"
	"time"
)

func Connect(userID uint64, clientName, username, password, ipaddr, mapKey, sshKey string) error {
	deskssh := sshDesktop.NewDesktopSSH()
	deskssh.SetLogger(log.New(os.Stderr, "[desktopssh] ", log.Ltime|log.Ldate))
	deskssh.SetUserName(username)
	deskssh.SetPassword(password)
	deskssh.SetIPAddress(ipaddr)
	deskssh.SetUserID(userID)
	deskssh.SetClientName(clientName)

	if len(sshKey) != 0 {
		singer, err := ssh.ParsePrivateKey([]byte(sshKey))
		if err != nil {
			return err
		}
		deskssh.Singer = singer
	}

	// 将客户端信息加密保存到redis
	var cacheDeskssh = sshDesktop.DesktopSSHCache{
		UserID:      userID,
		ClientName:  clientName,
		Username:    username,
		Password:    password,
		IpAddress:   ipaddr,
		PrivateyKey: sshKey,
	}
	desksshByte, err := json.Marshal(cacheDeskssh)
	if err != nil {
		logrus.Error("客户端对象JSON序列化失败", err)
		return err
	}

	encodeObj, err := openssl.AesECBEncrypt(desksshByte, []byte(config.Aes.Secret), openssl.PKCS7_PADDING)
	if err != nil {
		logrus.Error("客户端对象AES加密失败")
		return err
	}
	config.RDB.Set(context.Background(), "client:"+string(mapKey), encodeObj, time.Hour*2)

	// 创建客户端
	err = deskssh.CreateClient()
	if err != nil {
		return err
	}

	// 开启协程处理请求
	deskssh.HandleShell(mapKey)
	return nil
}

func ExecuteShell(shell, key string) string {
	sshDesktop.DesktopSSHInputMap[key] <- shell
	select {
	case data := <-sshDesktop.DesktopSSHOutputMap[key]:
		return data
	}
}
